<template>
  <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible" :width="600"
             :close-on-click-modal="false" draggable destroy-on-close>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
      <el-row :gutter="24">
        <el-col class="mb20">
          <el-form-item label="知识库" prop="datasetId">
            <el-select placeholder="请选择知识库" v-model="form.datasetId">
              <el-option :key="index" :label="item.name" :value="item.id" v-for="(item, index) in datasetList">
                {{ item.name }}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="mb20">
          <el-form-item label="来源" prop="sourceType">
            <el-radio-group v-model="form.sourceType">
              <el-radio :key="index" :label="item.value" border v-for="(item, index) in source_type">{{
                  item.label
                }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col class="mb20" v-if="form.sourceType === '2'">
          <el-form-item label="文件名" prop="name">
            <el-input placeholder="请输入文件名" v-model="form.name"/>
          </el-form-item>
        </el-col>
        <el-col class="mb20" v-if="form.sourceType === '2'">
          <el-form-item label="内容" prop="content">
            <el-input type="textarea" rows="10" maxlength="1800" show-word-limit placeholder="请输入文件内容" v-model="form.content"/>
          </el-form-item>
        </el-col>

        <el-col class="mb20" v-if="form.sourceType !== '2'">
          <el-form-item label="资料" prop="files">
            <upload-file
                :limit="500"
                @change="handleFileChange"
                :fileType="fileType"
            />
            <a class="link link-primary" v-if="form.sourceType === '3'"
               @click="downBlobFile('/admin//sys-file/local/file/qa.xlsx', {}, 'Q&A.xlsx')">Q&A Excel 模板下载</a>
          </el-form-item>
        </el-col>
        <el-col class="mb20">
          <el-form-item label="有效" prop="fileStatus">
            <el-radio-group v-model="form.fileStatus">
              <el-radio :key="index" :label="item.value" border v-for="(item, index) in yes_no_type">{{
                  item.label
                }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
        </span>
    </template>
  </el-dialog>

</template>

<script setup lang="ts" name="AiDocumentDialog">
import {useDict} from '/@/hooks/dict';
import {useMessage} from "/@/hooks/message";
import {getObj, addObj, putObj} from '/@/api/knowledge/aiDocument'
import {rule} from '/@/utils/validate';
import {fetchDataList} from "/@/api/knowledge/aiDataset";
import {downBlobFile} from "/@/utils/other";

const emit = defineEmits(['refresh']);

// 定义变量内容
const {yes_no_type, source_type} = useDict('yes_no_type', 'source_type')
const dataFormRef = ref();
const route = useRoute();
const visible = ref(false)
const loading = ref(false)
const fileType = ref(['jpeg', 'png', 'jpg', 'gif', 'md', 'doc', 'xls', 'ppt', 'txt', 'pdf', 'docx', 'xlsx', 'pptx', 'html'])
// 定义字典

// 提交表单数据
const form = reactive({
  id: '',
  name: '',
  datasetId: '',
  fileType: '',
  content: '',
  files: [],
  sourceType: '1',
  sliceCount: '',
  hitCount: '',
  fileSize: '',
  fileStatus: '1',
});

// 定义校验规则
const dataRules = ref({
  datasetId: [{required: true, message: '所属知识库不能为空', trigger: 'blur'}],
  files: [{required: true, message: '资料文件不能为空', trigger: 'blur'}],
  name: [{validator: rule.overLength, trigger: 'blur'}, {required: true, message: '文件名不能为空', trigger: 'blur'}],
  content: [{required: true, message: '内容不能为空', trigger: 'blur'}, {
    min: 100,
    max: 1800,
    message: '文本长度在 100 - 1800 之间',
    trigger: 'blur',
  }],
})
// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true
  form.id = ''
  form.files = []

  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });

  getDatasetList()

  // 获取aiDocument信息
  if (id) {
    form.id = id
    getAiDocumentData(id)
  }
};

// 监听 form.sourceType 变化，如果 sourceType === 1 则打开 excelUploadRef.show()
watch(() => form.sourceType, (value, oldValue) => {
  if (value === '3') {
    fileType.value = ['xlsx']
  } else {
    fileType.value = ['jpeg', 'png', 'jpg', 'gif', 'md', 'doc', 'xls', 'ppt', 'txt', 'pdf', 'docx', 'xlsx', 'pptx', 'html']
  }
});

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {
  });
  if (!valid) return false;

  try {
    loading.value = true;
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};

const datasetList = ref([])
const getDatasetList = async () => {
  const {data} = await fetchDataList()
  datasetList.value = data
}

const handleFileChange = (fileNames: String, fileList: any) => {
  form.files = fileList
}

// 初始化表单数据
const getAiDocumentData = (id: string) => {
  // 获取数据
  loading.value = true
  getObj(id).then((res: any) => {
    Object.assign(form, res.data)
  }).finally(() => {
    loading.value = false
  })
};


onMounted(() => {
  if (route.query.datasetId) {
    form.datasetId = route.query.datasetId
  }
})
// 暴露变量
defineExpose({
  openDialog
});
</script>
